<!-- components/account/EmailSettings.vue -->
<template>
  <div class="email-settings">
    <div class="current-email">
      <h4>当前绑定邮箱</h4>
      <p class="email-address">{{ currentEmail }}</p>
    </div>

    <el-divider />

    <div class="change-email">
      <h4>更换邮箱</h4>
      <el-form :model="form" label-width="100px" style="max-width: 500px;">
        <el-form-item label="新邮箱">
          <el-input v-model="form.newEmail" placeholder="请输入新邮箱地址" />
        </el-form-item>

        <el-form-item label="验证码">
          <div class="captcha-input">
            <el-input v-model="form.captcha" placeholder="请输入验证码" style="width: 200px;" />
            <el-button
                :disabled="countdown > 0"
                @click="sendCaptcha"
                style="margin-left: 10px;"
            >
              {{ countdown > 0 ? `${countdown}s后重新获取` : '获取验证码' }}
            </el-button>
          </div>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit">确认更换</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'

// 定义props接口
interface Props {
  email?: string
}

// 接收父组件传递的email属性
const props = withDefaults(defineProps<Props>(), {
  email: '--'
})

const currentEmail = ref(props.email)
const form = reactive({
  newEmail: '',
  captcha: ''
})
const countdown = ref(0)

// 监听props.email的变化
watch(() => props.email, (newEmail) => {
  currentEmail.value = newEmail
})

const sendCaptcha = () => {
  if (!form.newEmail) {
    ElMessage.warning('请输入邮箱地址')
    return
  }

  // 模拟发送验证码
  countdown.value = 60
  const timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)

  ElMessage.success('验证码已发送到邮箱')
}

const handleSubmit = () => {
  if (!form.newEmail || !form.captcha) {
    ElMessage.warning('请填写完整信息')
    return
  }

  // 模拟更换邮箱
  currentEmail.value = form.newEmail
  form.newEmail = ''
  form.captcha = ''
  ElMessage.success('邮箱更换成功')
}
</script>

<style scoped>
.email-settings {
  padding: 20px;
}

.current-email h4,
.change-email h4 {
  margin-bottom: 16px;
  color: #303133;
  font-weight: 600;
}

.email-address {
  font-size: 16px;
  color: #409EFF;
  font-weight: 500;
}

.captcha-input {
  display: flex;
  align-items: center;
}
</style>
